<template>
  <Modal
    class="roles"
    v-if="modals.roles && nonTravelers >= 1"
    @close="toggleModal('roles')"
  >
    <div v-if="!hasRoles" class="loading">
      {{ $t("roleSelection.loadingRoles") }}
    </div>
    <div v-else>
      <h3>
        {{ $t("roleSelection.selectCharacters", { count: nonTravelers }) }}
      </h3>
      <ul class="tokens" v-for="(teamRoles, team) in roleSelection" :key="team">
        <li class="count" :class="[team]">
          {{ teamRoles.reduce((a, { selected }) => a + selected, 0) }} /
          {{
            game[Math.max(0, nonTravelers - 5)]
              ? game[Math.max(0, nonTravelers - 5)][team]
              : 0
          }}
        </li>
        <li
          v-for="role in teamRoles"
          :class="[role.team, role.selected ? 'selected' : '']"
          :key="role.id"
          @click="role.selected = role.selected ? 0 : 1"
        >
          <Token :role="role" />
          <font-awesome-icon icon="exclamation-triangle" v-if="role.setup" />
          <div class="buttons" v-if="allowMultiple">
            <font-awesome-icon
              icon="minus-circle"
              @click.stop="role.selected--"
            />
            <span>{{ role.selected > 1 ? "x" + role.selected : "" }}</span>
            <font-awesome-icon
              icon="plus-circle"
              @click.stop="role.selected++"
            />
          </div>
        </li>
      </ul>
      <div class="warning" v-if="hasSelectedSetupRoles">
        <font-awesome-icon icon="exclamation-triangle" />
        <span>
          {{ $t("roleSelection.warningSetupRoles") }}
        </span>
      </div>
      <label class="multiple" :class="{ checked: allowMultiple }">
        <font-awesome-icon :icon="allowMultiple ? 'check-square' : 'square'" />
        <input type="checkbox" name="allow-multiple" v-model="allowMultiple" />
        {{ $t("roleSelection.allowDuplicateCharacters") }}
      </label>
      <div class="button-group">
        <div
          class="button"
          @click="assignRoles"
          :class="{
            disabled: selectedRoles > nonTravelers || !selectedRoles,
          }"
        >
          <font-awesome-icon icon="people-arrows" />
          {{
            $t("roleSelection.assignCharactersRandomly", {
              count: selectedRoles,
            })
          }}
        </div>
        <div class="button" @click="selectRandomRoles">
          <font-awesome-icon icon="random" />
          {{ $t("roleSelection.shuffleCharacters") }}
        </div>
      </div>
    </div>
  </Modal>
</template>

<script>
import Modal from "./Modal";
import gameJSON from "./../../game";
import Token from "./../Token";
import { mapGetters, mapMutations, mapState } from "vuex";
import i18n from "../../i18n";

const randomElement = (arr) => arr[Math.floor(Math.random() * arr.length)];

export default {
  components: {
    Token,
    Modal,
  },
  data: function () {
    return {
      roleSelection: {},
      game: gameJSON,
      allowMultiple: false,
    };
  },
  computed: {
    selectedRoles: function () {
      return Object.values(this.roleSelection)
        .map((roles) => roles.reduce((a, { selected }) => a + selected, 0))
        .reduce((a, b) => a + b, 0);
    },
    hasSelectedSetupRoles: function () {
      return Object.values(this.roleSelection).some((roles) =>
        roles.some((role) => role.selected && role.setup),
      );
    },
    hasRoles() {
      const hasRoles = this.roles && this.roles.size > 0;
      console.log(
        "hasRoles check:",
        hasRoles,
        "roles count:",
        this.roles ? this.roles.size : 0,
      );
      return hasRoles;
    },
    ...mapState(["roles", "modals"]),
    ...mapState("players", ["players"]),
    ...mapGetters({ nonTravelers: "players/nonTravelers" }),
  },
  methods: {
    $t(key, params = {}) {
      return i18n.t(key, params);
    },
    selectRandomRoles() {
      // 确保roles存在且有内容
      if (!this.roles || this.roles.size === 0) {
        console.log("No roles available for selection");
        return;
      }

      console.log("Initializing role selection with", this.roles.size, "roles");
      this.roleSelection = {};

      this.roles.forEach((role) => {
        if (!this.roleSelection[role.team]) {
          this.$set(this.roleSelection, role.team, []);
        }
        this.roleSelection[role.team].push(role);
        this.$set(role, "selected", 0);
      });

      delete this.roleSelection["traveler"];

      const playerCount = Math.max(5, this.nonTravelers);
      const composition =
        this.game[Math.max(0, playerCount - 5)] || this.game[0];

      console.log(
        "Using composition for",
        playerCount,
        "players:",
        composition,
      );

      Object.keys(composition).forEach((team) => {
        for (let x = 0; x < composition[team]; x++) {
          if (this.roleSelection[team]) {
            const available = this.roleSelection[team].filter(
              (role) => !role.selected,
            );
            if (available.length) {
              randomElement(available).selected = 1;
            }
          }
        }
      });

      console.log(
        "Role selection initialized:",
        Object.keys(this.roleSelection).length,
        "teams",
      );
    },
    assignRoles() {
      console.log(
        "assignRoles called, selectedRoles:",
        this.selectedRoles,
        "nonTravelers:",
        this.nonTravelers,
      );
      if (this.selectedRoles <= this.nonTravelers && this.selectedRoles) {
        // generate list of selected roles and randomize it
        const roles = Object.values(this.roleSelection)
          .map((roles) =>
            roles
              // duplicate roles selected more than once and filter unselected
              .reduce((a, r) => [...a, ...Array(r.selected).fill(r)], []),
          )
          // flatten into a single array
          .reduce((a, b) => [...a, ...b], [])
          // 过滤掉无效的角色
          .filter((role) => role && typeof role === "object")
          .map((a) => [Math.random(), a])
          .sort((a, b) => a[0] - b[0])
          .map((a) => a[1]);

        // 分配角色给玩家
        this.players.forEach((player) => {
          if (player.role.team !== "traveler" && roles.length) {
            const value = roles.pop();
            this.$store.commit("players/update", {
              player,
              property: "role",
              value,
            });
          }
        });

        // 自动分配恶魔伪装
        this.assignDemonBluffs();

        // 自动重新开始游戏历史
        this.autoRestartGameHistory();

        this.$store.commit("toggleModal", "roles");
      }
    },

    // 自动分配恶魔伪装
    assignDemonBluffs() {
      console.log("开始自动分配恶魔伪装");

      // 获取所有未选择的角色
      const unselectedRoles = [];
      Object.values(this.roleSelection).forEach((teamRoles) => {
        teamRoles.forEach((role) => {
          // 计算未选择的数量
          const unselectedCount =
            role.selected === 0
              ? 1
              : role.selected > 0
              ? 0
              : Math.abs(role.selected);

          for (let i = 0; i < unselectedCount; i++) {
            unselectedRoles.push(role);
          }
        });
      });

      console.log("未选择的角色数量:", unselectedRoles.length);

      if (unselectedRoles.length === 0) {
        console.log("没有未选择的角色，无法分配恶魔伪装");
        return;
      }

      // 按团队分类未选择的角色
      const unselectedByTeam = {
        townsfolk: unselectedRoles.filter((role) => role.team === "townsfolk"),
        outsider: unselectedRoles.filter((role) => role.team === "outsider"),
        minion: unselectedRoles.filter((role) => role.team === "minion"),
        demon: unselectedRoles.filter((role) => role.team === "demon"),
        fabled: unselectedRoles.filter((role) => role.team === "fabled"),
      };

      console.log("按团队分类的未选择角色:", unselectedByTeam);

      // 选择恶魔伪装：两个镇民 + 一个外来者
      const bluffs = [];

      // 选择两个镇民
      if (unselectedByTeam.townsfolk.length >= 2) {
        const selectedTownsfolk = this.getRandomRoles(
          unselectedByTeam.townsfolk,
          2,
        );
        bluffs.push(...selectedTownsfolk);
        console.log(
          "选择的镇民伪装:",
          selectedTownsfolk.map((r) => r.name),
        );
      } else if (unselectedByTeam.townsfolk.length === 1) {
        bluffs.push(unselectedByTeam.townsfolk[0]);
        console.log("选择的镇民伪装:", unselectedByTeam.townsfolk[0].name);
      }

      // 选择一个外来者
      if (unselectedByTeam.outsider.length >= 1) {
        const selectedOutsider = this.getRandomRoles(
          unselectedByTeam.outsider,
          1,
        );
        bluffs.push(...selectedOutsider);
        console.log(
          "选择的外来者伪装:",
          selectedOutsider.map((r) => r.name),
        );
      }

      // 如果镇民和外来者不够，用其他角色补充
      const remainingSlots = 3 - bluffs.length;
      if (remainingSlots > 0) {
        const remainingRoles = [
          ...unselectedByTeam.townsfolk,
          ...unselectedByTeam.outsider,
          ...unselectedByTeam.minion,
          ...unselectedByTeam.demon,
        ].filter((role) => !bluffs.includes(role));

        if (remainingRoles.length > 0) {
          const additionalBluffs = this.getRandomRoles(
            remainingRoles,
            Math.min(remainingSlots, remainingRoles.length),
          );
          bluffs.push(...additionalBluffs);
          console.log(
            "补充的伪装:",
            additionalBluffs.map((r) => r.name),
          );
        }
      }

      // 设置恶魔伪装
      if (bluffs.length > 0) {
        console.log(
          "最终恶魔伪装:",
          bluffs.map((r) => r.name),
        );
        this.$store.commit("players/setBluff", { bluffs });
      } else {
        console.log("无法分配恶魔伪装");
        this.$store.commit("players/setBluff", { bluffs: [] });
      }
    },

    // 从角色数组中随机选择指定数量的角色
    getRandomRoles(roles, count) {
      const shuffled = [...roles].sort(() => Math.random() - 0.5);
      return shuffled.slice(0, count);
    },

    // 自动重新开始游戏历史记录
    autoRestartGameHistory() {
      console.log("🎮 角色分配完成，自动重新开始游戏历史");
      
      // 清除历史记录
      this.$store.commit("clearHistory");

      // 重置游戏状态
      this.$store.commit("resetGameState");

      // 确保切换到夜晚阶段
      if (!this.$store.state.grimoire.isNight) {
        this.$store.commit("toggleNight");
      }

      // 设置为首夜
      this.$store.commit("setCurrentRound", 1);
      this.$store.commit("setCurrentPhase", "night");

      // 记录游戏开始和角色分配完成
      this.$store.commit("addHistoryEvent", {
        action: "game_start",
        summary: "新游戏开始",
        details: "说书人分配角色完成，游戏正式开始，进入首夜阶段",
        phase: "night",
        round: "first_night",
        isPublic: false,
      });

      // 记录角色分配事件
      this.$store.commit("addHistoryEvent", {
        action: "roles_assigned",
        summary: "角色随机分配完成",
        details: `说书人为 ${this.nonTravelers} 名玩家随机分配了角色`,
        phase: "setup",
        round: "setup",
        isPublic: false,
      });

      console.log("✅ 游戏历史重新开始完成");
    },

    ...mapMutations(["toggleModal"]),
  },
  mounted: function () {
    console.log(
      "RolesModal mounted, roles count:",
      this.roles ? this.roles.size : 0,
    );
    // 在mounted时检查roles是否已经准备好
    if (
      this.roles &&
      this.roles.size > 0 &&
      !Object.keys(this.roleSelection).length
    ) {
      this.$nextTick(() => {
        this.selectRandomRoles();
      });
    }
  },
  activated() {
    console.log(
      "RolesModal activated, roles count:",
      this.roles ? this.roles.size : 0,
    );
    // 当模态框被激活时，确保角色列表已初始化
    if (this.roles && this.roles.size > 0) {
      this.$nextTick(() => {
        this.selectRandomRoles();
      });
    }
  },
  watch: {
    roles: {
      handler(newRoles, oldRoles) {
        console.log(
          "Roles changed:",
          newRoles ? newRoles.size : 0,
          "old:",
          oldRoles ? oldRoles.size : 0,
        );
        // 确保roles有内容后再初始化
        if (this.roles && this.roles.size > 0) {
          this.$nextTick(() => {
            this.selectRandomRoles();
          });
        } else {
          // 如果roles为空，清空roleSelection
          this.roleSelection = {};
        }
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../vars.scss";

.loading {
  text-align: center;
  padding: 20px;
  color: white;
  font-size: 120%;
  font-style: italic;
}

ul.tokens {
  padding-left: 5%;
  li {
    border-radius: 50%;
    width: 5vw;
    margin: 5px;
    opacity: 0.5;
    transition: all 300ms cubic-bezier(0.4, 0, 0.2, 1);
    transform: scale(1);
    &:hover {
      transform: scale(1.1);
      z-index: 15;
    }
    &.selected {
      opacity: 1;
      transform: scale(1.1);
      box-shadow: 0 0 20px rgba(0, 0, 0, 0.8);
      .buttons {
        display: flex;
      }
      .fa-exclamation-triangle {
        display: block;
      }
    }
    &.townsfolk {
      box-shadow:
        0 0 10px $townsfolk,
        0 0 10px #004cff;
    }
    &.outsider {
      box-shadow:
        0 0 10px $outsider,
        0 0 10px $outsider;
    }
    &.minion {
      box-shadow:
        0 0 10px $minion,
        0 0 10px $minion;
    }
    &.demon {
      box-shadow:
        0 0 10px $demon,
        0 0 10px $demon;
    }
    &.traveler {
      box-shadow:
        0 0 10px $traveler,
        0 0 10px $traveler;
    }
    &:hover {
      transform: scale(1.2);
      z-index: 10;
    }
    .fa-exclamation-triangle {
      position: absolute;
      color: red;
      filter: drop-shadow(0 0 3px black) drop-shadow(0 0 3px black);
      top: 5px;
      right: -5px;
      font-size: 150%;
      display: none;
    }
    .buttons {
      display: none;
      position: absolute;
      top: 95%;
      text-align: center;
      width: 100%;
      z-index: 30;
      font-weight: bold;
      filter: drop-shadow(0 0 5px rgba(0, 0, 0, 1));
      span {
        flex-grow: 1;
      }
      svg {
        opacity: 0.25;
        cursor: pointer;
        &:hover {
          opacity: 1;
          color: red;
        }
      }
    }
  }
  .count {
    opacity: 1;
    position: absolute;
    left: 0;
    font-weight: bold;
    font-size: 75%;
    width: 5%;
    display: flex;
    align-items: center;
    justify-content: center;
    &:after {
      content: " ";
      display: block;
      padding-top: 100%;
    }
    &.townsfolk {
      color: $townsfolk;
    }
    &.outsider {
      color: $outsider;
    }
    &.minion {
      color: $minion;
    }
    &.demon {
      color: $demon;
    }
  }
}

.roles .modal {
  .multiple {
    display: block;
    text-align: center;
    cursor: pointer;
    &.checked,
    &:hover {
      color: red;
    }
    &.checked {
      margin-top: 10px;
    }
    svg {
      margin-right: 5px;
    }
    input {
      display: none;
    }
  }

  .warning {
    color: red;
    position: absolute;
    bottom: 20px;
    right: 20px;
    z-index: 10;
    svg {
      font-size: 150%;
      vertical-align: middle;
    }
    span {
      display: none;
      text-align: center;
      position: absolute;
      right: -20px;
      bottom: 30px;
      width: 420px;
      background: rgba(0, 0, 0, 0.75);
      padding: 5px;
      border-radius: 10px;
      border: 2px solid black;
    }
    &:hover span {
      display: block;
    }
  }
}
</style>
